﻿// MembersService.cs
//

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.ServiceModel.DomainServices.EntityFramework;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using BookClub.Web.DataModel;
using BookClub.Web.WebServices;
using System.ServiceModel.DomainServices.Server.ApplicationServices;

namespace BookClub.Web.Services {

    // This service represents the members in the book club
    [EnableClientAccess]
    [RequiresAuthentication]
    [RequiresRole("Admin")]
    public class MembersService : LinqToEntitiesDomainService<BookClubEntities> {

        public IQueryable<Member> GetMembers() {
            return ObjectContext.Members.OrderBy(m => m.MemberID);
        }

        public void AddMember(Member member) {
            // Validate that the member alias doesn't already exist
            if (MemberExists(member.MemberAlias)) {
                throw new ValidationException("A member with that alias already exists and cannot be added.");
            }

            member.JoinDate = DateTime.UtcNow.Date;
            member.LoginDate = DateTime.MinValue.Date;
            member.IsAdmin = false;
            member.PasswordHash = Authentication.HashPassword(member.Password);

            ObjectContext.Members.AddObject(member);
        }

        public bool MemberExists(string memberAlias) {
            bool memberExists = false;

            using (BookClubEntities db = new BookClubEntities()) {
                memberExists = db.Members.Any(m => m.MemberAlias == memberAlias);
            }
            return memberExists;
        }
    }
}
